from periphery import PWM
import time

class Motor:
    def __init__(self,chipa,ma,chipb,mb):
        # 打开PWM芯片
        self.pwma = PWM(chipa, ma)
        self.pwmb = PWM(chipb, mb)

        # 设置频率
        self.pwma.frequency = 1000
        self.pwmb.frequency = 1000

        # 设置极性
        self.pwma.polarity = "inversed"
        self.pwmb.polarity = "inversed"

        # 设置占空比为0
        self.pwma.duty_cycle = 0
        self.pwmb.duty_cycle = 0

        # 启用PWM
        self.pwma.enable()
        self.pwmb.enable()

    def write(self,speed):
        if(speed>=0):
            self.pwma.duty_cycle=abs(speed)
            self.pwmb.duty_cycle=0
        else:
            self.pwma.duty_cycle=0
            self.pwmb.duty_cycle=abs(speed)

    def deinit(self):

        # 关闭PWM
        self.pwma.disable()
        self.pwmb.disable()
        self.pwma.close()
        self.pwmb.close()

motor=Motor(0,0,1,0)
motor.write(0.5)
time.sleep(1)
motor.write(0)
time.sleep(1)
motor.write(-0.5)
time.sleep(1)
motor.deinit()
